<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React 新生命周期 getSnapshotBeforeUpdate 小例</title>
    <style>
        .list {
            width: 200px;
            height: 150px;
            background-color: skyblue;
            overflow: auto;
        }

        .news {
            height: 30px;
        }
    </style>
</head>
<body>

<div id="show"></div>

<script src="js/react.development.js" crossorigin></script>
<script src="js/react-dom.development.js" crossorigin></script>
<script src="js/babel.js"></script>
<script type="text/babel">
    class Snapshot extends React.Component {

        state = {newsArr: []}

        componentDidMount() {
            setInterval(() => {
                let {newsArr} = this.state;
                let nes = 'news' + (newsArr.length + 1);
                this.setState({newsArr: [nes, ...newsArr]})
            }, 1000);
        }

        getSnapshotBeforeUpdate() {
            return this.refs.list.scrollHeight;
        }

        componentDidUpdate(preProps, preState, height) {
            this.refs.list.scrollTop += this.refs.list.scrollHeight - height
        }

        render() {
            return (
                <div className="list" ref="list">
                    {this.state.newsArr.map((n, index) => {
                        return <div key={index} className="news">{n}</div>
                    })}
                </div>

            );
        }

    }

    ReactDOM.render(<Snapshot/>, document.getElementById('show'));
</script>
</body>
</html>